function signout(){
	parent.$.messager.confirm('确认对话框', '确认退出登录？', function(r) {
		if (r) {
			var data = postAsyncAjax("/exitLogin", null);
			if (data.returnCode == "00") {
				window.top.location.href ="/index";
			}
		}
	});
}


function addAccordion(id,title,content,icon,sum){
	if(sum==1){
		$('#'+id).accordion('add', {
			title: title,
			iconCls:icon,
			content: content,
			selected: true
		});
	}else{
		$('#'+id).accordion('add', {
			title: title,
			iconCls:icon,
			content: content,
			selected: false
		});
	}
	
}

function serializeJson(form){ 
    var serializeObj={}; 
    var array=form.serializeArray(); 
    // var str=this.serialize();
    $(array).each(function(){ // 遍历数组的每个元素
            if(serializeObj[this.name]){ // 判断对象中是否已经存在 name，如果存在name
                  if($.isArray(serializeObj[this.name])){ 
                         serializeObj[this.name].push(this.value); // 追加一个值
																	// hobby :
																	// ['音乐','体育']
                  }else{ 
                          // 将元素变为 数组 ，hobby : ['音乐','体育']
                          serializeObj[this.name]=[serializeObj[this.name],this.value]; 
                  } 
            }else{ 
            	if (this.value !=="") {
            		serializeObj[this.name]=this.value; // 如果元素name不存在，添加一个属性
														// name:value
				}
            } 
    }); 
    return serializeObj; 
};
function gridReload(id) {
	var win = top.$("#headFrame").get(0).contentWindow;
	var taba = win.$("#menutab").tabs('getSelected'); // 获取选择的面板
	var title = taba.panel("options").tab.text();
	win.$("#" + title).get(0).contentWindow.$("#" + id).datagrid('load');

	// parent.$("#content").get(0).contentWindow.$("#"+id).datagrid('load');
	// var taba = parent.$("#menutab").tabs('getSelected'); // 获取选择的面板
	// var title = taba.panel("options").tab.text();
	// parent.$("#"+title).get(0).contentWindow.$("#"+id).datagrid('load');
	// frames["content"].$("#"+_id).datagrid('load');
	// parent.$("iframe[name='headFrame']").get(0).contentWindow.$("#content").get(0).contentWindow.$("#alipayConfigList").datagrid('load');
}


// 顶级窗口打开方式
function topWindow(url, title, options) {
	setWindowSrc(url);
	setWindowAttr(title, options);
	openIframeWindow();
}

/** window* */
function closeIframeWindow() {
	top.$('#otherInfoIframeWindow').window('close');
}
function openIframeWindow() {
	// top.$("#headFrame").get(0).contentWindow.$('#otherInfoIframeWindow').attr("iconCls","icon-add");
// top.$("#headFrame").get(0).contentWindow.$('#otherInfoIframeWindow')
// .window('open');
	top.$('#otherInfoIframeWindow').window('open');
}
/** show message** */
function showMessage(message, options) {
	if (!options) {
		options = new Object();
	}
	options.msg = message;
	if (!options.title) {
		options.title = "提示信息";
	}
	if (!options.timeout) {
		options.timeout = "3000";
	}
	$.messager.show(options);
}
/*******************************************************************************
 * 设置窗口属性
 * 
 * @参数 title 标题
 * @参数 options Set panel size and do layout. The options object contains
 *     following properties: width: the new panel width height: the new panel
 *     height left: the new panel left position top: the new panel top position
 ******************************************************************************/
function setWindowAttr(title, options) {
	try {
		options.left = (window.screen.width - options.width) / 2;
		options.top = (window.screen.height - options.height) / 2 - 45;
	} catch (e) {
	}
	top.$('#otherInfoIframeWindow').window('setTitle', title);
	top.$('#otherInfoIframeWindow').window('resize', options);
}

/** 设置window信息 */
function setWindowSrc(url) {
	if (!url) {
		return;
	}
	top.$('#otherInfoIframe').attr("src",url);
}

/*
 * 获取异步AJAX
 */
function getAsyncAjax(url, data) {
	var json = null;
	$.ajax({
		type : "GET",
		url : url,
		data : data,
		async : false,
		success : function(msg) {
			json = msg;
		},
		error : function(request) {
			alert("加载超时！");
		}
	});
	return json;
}
/*
 * 获取异步AJAX
 */
function getAsyncAjaxTrue(url, data) {
	
	var json = null;
	$.ajax({
		type : "POST",
		url : url,
		data : data,
		async : true,
		success : function(msg) {
			json = msg;
		},
		error : function(request) {
			alert("加载超时！");
		}
	});
	return json;
}
/*
 * 获取异步AJAX
 */
function postAsyncAjaxTrue(url, data) {
	
	var json = null;
	$.ajax({
		type : "POST",
		url : url,
		data : data,
		async : true,
		success : function(msg) {
			if(msg.toString().indexOf("window")>0)window.top.location.href='/index';
			json = msg;
		},
		error : function(request) {
			alert("加载超时！");
		}
	});
	return json;
}

/*
 * 获取异步AJAX
 */
function postAsyncAjaxHeaders(url, data) {
	var json = null;
	$.ajax({
		type : "POST",
		headers:{"Content-Type":"application/x-www-form-urlencoded"},
		url : url,
		data : data,
		async : true,
		success : function(msg) {
			if(msg.toString().indexOf("window")>0)window.top.location.href='/index';
			json = msg;
		}
	});
	return json;
}

/*
 * 获取异步AJAX
 */
function postAsyncAjax(url, data) {
	var json = null;
	$.ajax({
		type : "POST",
		url : url,
		data : data,
		async : false,
		success : function(msg) {
			if(msg.toString().indexOf("alert")>0 ){
				$.messager.alert('提示',msg,'info',function(){
					if(msg.toString().indexOf("异地登录")>0 || msg.toString().indexOf("超时")>0){
						window.top.location.href='/index';
					}
				});
			}
			
			if(msg.toString().indexOf("window")>0)window.top.location.href='/index';
			json = msg;
		},error : function(request) {
			json = request;
		}
	});
	return json;
}

/*
 * 获取异步AJAX
 */
function postAsyncAjaxText(url, data) {
	var json = null;
	$.ajax({
		type : "POST",
		url : url,
		data : data,
		async : false,
		dataType: "text",
		success : function(msg) {
			if(msg.toString().indexOf("alert")>0 ){
				$.messager.alert('提示',msg,'info',function(){
					if(msg.toString().indexOf("异地登录")>0 || msg.toString().indexOf("超时")>0){
						window.top.location.href='/index';
					}
				});
			}
			if(msg.toString().indexOf("window")>0){window.top.location.href='/index';}
	
			msg = $.parseJSON(msg);
			json = msg;
		},error : function(request) {
			json = request;
		}
	});
	return json;
}


function postSubmit(url, fromId) {
	var json = null;
	$("#" + fromId).form('submit', {
		url : url,
		success : function(data) {
			json = data.returnCode;
		}
	});
	return json;
}

function postAjaxSubmit(url, fromId) {
	var json = null;
	var options = {
		url : url,
		async : false,
		cache : false,
		type : 'POST',
		data : $("#" + fromId).serialize(),
		success : function(data) {
			json = data;
		}
	};
	$("#" + fromId).ajaxSubmit(options);
	return json;
}
/**
 * 页面时间运算
 * 
 * @param date
 *            当前日期
 * @param days
 *            1为加一天 -1为减一天
 * @returns {String}
 */
function addDate(date, days) {
	var d = new Date(date);
	d.setDate(d.getDate() + days);
	var m = d.getMonth() + 1;
	m = d.getFullYear() + '-' + m + '-';
	if(d.getDate()<10){
		m+="0"+ d.getDate();
	}else{
		m+=d.getDate();
	}
	return m;
}


/**
 * 页面时间运算
 * 
 * @param date
 *            当前日期
 * @param days
 *            1为加一天 -1为减一天
 * @returns {String}
 */
function addDateHH(date, days) {
	var d = new Date(date);
	d.setDate(d.getDate() + days);
	var m = d.getMonth() + 1;
	var dd;
	if(d.getDate()<10){
		dd="0"+ d.getDate();
	}else{
		dd=d.getDate();
	}
	return d.getFullYear() + '-' + m + '-' + dd+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
}


/** 页面求合计 */
function compute(param) {
	var rows = table.datagrid('getRows')
	if (rows.length == 0)
		return 0;
	var total = 0;
	for (var i = 0; i < rows.length; i++) {
		total += parseInt(rows[i][param]);
	}
	return "<font color='red'>" + total + "</font>";
}

/**
 * 页面日期转换
 */
Date.prototype.Format = function(fmt) { // author: meizz
	var o = {
		"M+" : this.getMonth() + 1, // 月份
		"d+" : this.getDate(), // 日
		"h+" : this.getHours(), // 小时
		"m+" : this.getMinutes(), // 分
		"s+" : this.getSeconds(), // 秒
		"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
		"S" : this.getMilliseconds()
	// 毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	for ( var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])
					: (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

dateDiff = function(interval, date1, date2) {
	var objInterval = {
		'D' : 1000 * 60 * 60 * 24,
		'H' : 1000 * 60 * 60,
		'M' : 1000 * 60,
		'S' : 1000,
		'T' : 1
	};
	interval = interval.toUpperCase();
	var dt1 = Date.parse(date1.replace(/-/g, '/'));
	var dt2 = Date.parse(date2.replace(/-/g, '/'));
	try {
		return Math.round((dt2 - dt1) / eval('(objInterval.' + interval + ')'));
	} catch (e) {
		return e.message;
	}
}

/**
 * 页面参数传递
 */
var request = {
	QueryString : function(val) {
		var uri = window.location.search;
		var re = new RegExp("" + val + "\=([^\&\?]*)", "ig");
		return ((uri.match(re)) ? (uri.match(re)[0].substr(val.length + 1))
				: null);
	},
	QueryStrings : function() {
		var uri = window.location.search;
		var re = /\w*\=([^\&\?]*)/ig;
		var retval = [];
		while ((arr = re.exec(uri)) != null)
			retval.push(arr[0]);
		return retval;
	},
	setQuery : function(val1, val2) {
		var a = this.QueryStrings();
		var retval = "";
		var seted = false;
		var re = new RegExp("^" + val1 + "\=([^\&\?]*)$", "ig");
		for (var i = 0; i < a.length; i++) {
			if (re.test(a[i])) {
				seted = true;
				a[i] = val1 + "=" + val2;
			}
		}
		retval = a.join("&");
		return "?" + retval
				+ (seted ? "" : (retval ? "&" : "") + val1 + "=" + val2);
	}
}

closeDialog = function() {
	top.$('#myModal').modal('hide');
}

/*
 * String.prototype.format= function(){ var args = arguments; return
 * this.replace(/\{(\d+)\}/g,function(s,i){ return args[i]; }); }
 */

Array.prototype.indexOf = function(val) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == val)
			return i;
	}
	return -1;
};

Array.prototype.remove = function(val) {
	var index = this.indexOf(val);
	if (index > -1) {
		this.splice(index, 1);
	}
};

function addTab(params) {

	var menutab = top.$("#headFrame").get(0).contentWindow.$("#menutab");
	
	var ifexist =menutab.tabs('exists',params.text);
	if (!ifexist) {
	
	var iframe = '<iframe src="' + params.url + '" frameborder="0" id='
			+ params.text
			+ ' style="border:0;width:100%;height:100%;"></iframe>';

	menutab.tabs('add', {
		title : params.text,
		content : iframe,
		fit : true,
		
		closable : true,
		tools : [ {
			iconCls : 'icon-mini-refresh',
			handler : function() {
				menutab.tabs('getSelected').panel('refresh');
			}
		} ]
	});
	
	
	}else{
		// 选择已存在的面板
		menutab.tabs('select',params.text);
	}
}


function limitButton(parentCode) {
	// 按钮(添加，修改，删除)
	var data = postAsyncAjax("/selectLimitsByUserIdAndParentCode", {
		parentCode : parentCode
	});
	if (data.data == null)data.data = [];
	var arr = data.data;
	if(arr==undefined){window.top.location.reload();}
	var param = [];
	var addrArray = [];
	for (var i = 0; i < arr.length; i++) {
		addrArray[arr[i].name] = arr[i].addr;
		param.push({
			code:arr[i].code,
			text : arr[i].name,
			iconCls : arr[i].icon,
			handler : function() {
				eval(addrArray[$(this).text()]);
			}
		})
	}
	return param;
}

function limitCodeButton(parentCode) {
	// 按钮(添加，修改，删除)
	var data = postAsyncAjax("/selectLimitsByUserIdAndParentCode", {
		parentCode : parentCode
	});
	if (data.data == null)data.data = [];
	var arr = data.data;
	if(arr==undefined){window.top.location.reload();}
	var param = [];
	var addrArray = [];
	for (var i = 0; i < arr.length; i++) {
		addrArray[arr[i].name] = arr[i].addr;
		param.push({
			id : "btn"+arr[i].code,
			code:arr[i].code,
			text : arr[i].name,
			iconCls : arr[i].icon,
			handler : function() {
				eval(addrArray[$(this).text()]);
			}
		})
	}
	return param;
}

/**
 * 弹出顶置新窗口
 * @param popurl		新窗口的地址
 * @param popTitle		新窗口标题
 * @param popWidth		新窗口宽度
 * @param popHeight		新窗口高度
 * @param options		用于传递给下个窗口的变量或者函数（新窗口用parentWinowOption.变量名或者方法名  可调用父窗口的变量或方法）
 * @returns
 */
function openTopWindow(popurl,popTitle,popWidth,popHeight,options) {
    var url = popurl ;//POP框URL
    var popW =  popWidth;//POP框宽度
    var popH =  popHeight;//POP框高度
    var popT =  popTitle;//POP框标题
	if (!options) {
		options = new Object();
	}
    var popDialog = top.$('<div />').dialog({
        title : popT,
        content : '<iframe id="" src="' + url + '" allowTransparency="true"  scrolling="auto" width="100%" height="98%" frameBorder="0" name=""></iframe>',
        width : popW,
        height : popH,
        modal : true,
        maximizable : true,
        resizable : true,
        onClose : function() {
            popDialog.dialog('destroy').remove();
        }
    });
    // 定义关闭窗口方法供下个窗口关闭
    options.closeIframeWindow = function(){
    	popDialog.dialog('close',true);
    }
    // 给新窗口定义变量传递参数或方法
	popDialog.find('iframe').get(0).contentWindow.parentWinowOption = options;
}




//字典项工具类
var dictTools = {
	//获取字典项数据，统一获取入口
	getData : function() {
		if(this.data==null){
			this.data={};
		}
		return this.data;
	},
	//添加新的字典数组
	addDictData : function(data,dictCode,valCol,nameCol){
		var arr = new Array();
		for(var i=0;i<data.length;i++){
			var dict = new Object();
			dict.name = eval("data["+i+"]."+nameCol);
			dict.code = eval("data["+i+"]."+valCol);
			arr.push(dict);
		}
		this.getData()[dictCode] = arr;
	},
	//查询字典表缓存字典数据
	queryDictData : function(sortCodes){
		if(sortCodes==null){
			return;
		}
		var param = {};
		param.sortCodes = sortCodes;
		var result = postAsyncAjax('/findDictCodeList', param);
		var list = result;
		var data = {};
		for(var i=0;i<list.length;i++){
			var obj = list[i];
			var arr = data[obj.sortCode];
			if(arr == null){
				arr = new Array();
			}
			var dict = new Object();
			dict.code = obj.code;
			dict.name = obj.name;
			arr.push(dict);
			data[obj.sortCode]=arr;
		}
		$.extend(true,this.getData(),data);
	},
	//获取字典数组
	getDictData : function(dictCode){
		var dict = this.getData()[dictCode];
		if(dict==null){
			return new Array();
		}
		return dict;
	},
	//根据code获取中文
	getDictName : function(dictCode,code){
		if(null == code){
			return '';
		}
		var dict = this.getDictData(dictCode);
		for(var i=0;i<dict.length;i++){
			if(code == dict[i].code){
				return dict[i].name;
			}
		}
		return code;
	},
	//标签加载字典项
	loadDictData :function(box,dictCode,width){
		var sortCodeBox = box;
		var dictData = this.getDictData(dictCode);
		var dict = JSON.parse(JSON.stringify(dictData));
		var obj = {};
		obj.code = ''
		obj.name = '-请选择-';
		dict.unshift(obj);
		if(width == null || width ==''){
			width=150;
		}
		sortCodeBox.combobox({
			width : width,
			panelHeight : "auto",
			data : dict,
			valueField : 'code',
			textField : 'name',
			editable : false,
	        onSelect: function(record){
	        },
	        onLoadSuccess: function(record){
	        	sortCodeBox.combobox('setValue', '');
	        }
		});
	},
	// 动态下拉框
	sortCodeSelect:function(width) {
		var sortCodeSelectList = $(".sortCodeSelect");
		for (var i = 0; i < sortCodeSelectList.length; i++) {
			var sortCodeBox = $(sortCodeSelectList[i]);
			this.loadDictData(sortCodeBox,sortCodeBox.attr("sortCode"),width);
		}

	}
}

/**
 * 显示遮罩层
 * @param msg
 * @returns
 */
function mask(msg){
	if(msg == null || msg == ''){
		msg = "加载中...";
	}
	var body = $("body");
	$("<div class=\"datagrid-mask\" style=\"display:block\"></div>").appendTo(body);
	var msg=$("<div class=\"datagrid-mask-msg\" style=\"display:block;left:50%\"></div>").html(msg).appendTo(body);
	msg._outerHeight(40);
	msg.css({marginLeft:(-msg.outerWidth()/2),lineHeight:(msg.height()+"px")});
}
/**
 * 移除遮罩层
 * @returns
 */
function unmask(){
	var body = $("body");
	body.children("div.datagrid-mask-msg").remove();
	body.children("div.datagrid-mask").remove();
}